import { Editor, ShortcutKey } from 'amis-editor';
import React, { useContext, useRef } from 'react';
import {
  Layout, Button, cssVar, udp, Input, useAsyncEffect, message, Select,
} from '@cscec/udp-ui';
import { CodepenCircleOutlined, EyeOutlined, SaveOutlined } from '@ant-design/icons';
import { getAmisEnv, schemaUtil } from '@/components/editor/util';
import { useEditorPanel } from '@/components/editor/panel';
import { getEnableWorkbenchType, getWorkbenchTemplateById, saveOrUpdateWorkbenchTemplate } from './service';
import { portalWrapper, useAmisReWrite } from '../common';
import { buildRenderers } from '@/components/editor/plugin';
import type { IStore } from './type';

import '../style.less';
import { type IDCtx, DesignContext } from '@/components/editor/context';

function Header() {
  const { store, setStore } = useContext<IDCtx<IStore>>(DesignContext);

  const onPreview = () => {
    schemaUtil.setData({ ...store.value, amisPackages: store.packages });
    const appTitle = `${udp.getQueryValue('appTitle') || '门户模板'}-预览`;
    udp.open('/portal/preview', {
      outLink: !udp.isRunMaster, preview: 1, type: 'template', ...udp.getQueryValue(''), id: '', AppTitle: appTitle,
    });
  };

  const getHandle = (useFlg: number = 0) => async () => {
    if (!store.title) {
      message.warn('模板名称不能为空！');
      return;
    }
    if (!store.typeId) {
      message.warn('模板分类不能为空！');
      return;
    }
    const key = await saveOrUpdateWorkbenchTemplate({
      id: store.id,
      workbenchName: store.title,
      typeId: store.typeId,
      workbenchContent: udp.jsonString({ ...store.value, amisPackages: store.packages }),
      useFlg,
    });
    setStore({ id: key, useFlg });
    if (key) {
      const refreshKey = udp.getQueryValue('refreshKey');
      refreshKey && udp.refreshList(refreshKey, { id: key, type: 'save' });
      setStore({ id: key, useFlg });
    }
  };

  return (
    <div className="Editor-header">
      <div className="Editor-title">
        <CodepenCircleOutlined style={{ color: cssVar.primaryColor, marginRight: 4, fontSize: 18 }} />
        <Input style={{ margin: '0 24px 0 12px', width: 160 }} value={store.title} onChange={(title) => setStore({ title })} />
        <Select
          valueField="id"
          labelField="typeName"
          value={store.typeId}
          labelInValue={false}
          placeholder="模板分类"
          style={{ margin: '0 24px 0 0', width: 160 }}
          request={getEnableWorkbenchType}
          onChange={(typeId) => setStore({ typeId })}
        />
      </div>
      <div className="Editor-header-actions">
        <ShortcutKey />
        <Button
          className="m-l"
          icon={<EyeOutlined />}
          onClick={onPreview}
        >
          预览
        </Button>
        <Button
          className="m-l"
          type='primary'
          onClick={getHandle()}
          icon={<SaveOutlined />}
        >
          保存
        </Button>
      </div>
    </div>
  );
}

function TemplateDesign({ plugins }: { plugins?: any; }) {
  const amisRef = useRef<Editor>(null);
  const { store, setStore } = useContext<IDCtx<IStore>>(DesignContext);

  const onChange = (value: any) => {
    schemaUtil.setData(value);
    setStore({ value });
  };

  useEditorPanel('portal');

  useAsyncEffect(async () => {
    const result = await getWorkbenchTemplateById({ id: udp.getQueryValue('id') });
    await buildRenderers(result?.packages, amisRef.current?.manager);
    setStore({
      ...result, loading: false, packages: result?.packages, session: 'design',
    });
  }, []);

  useAmisReWrite(amisRef);

  return (
    <Layout className="Editor-Container" loading={store.loading}>
      <Header />
      <Layout.Flex className="Editor-inner">
        <Editor
          key="editor"
          ref={amisRef}
          theme="antd"
          value={store.value}
          onChange={onChange}
          isMobile={false}
          className="is-fixed"
          plugins={plugins}
          showCustomRenderersPanel
          amisEnv={getAmisEnv('design')}
        />
      </Layout.Flex>
    </Layout>

  );
}

export default portalWrapper(TemplateDesign, { isDesign: true });
